package server

import (
	"../base"
	"../net"
	"encoding/json"
	//"fmt"
	"strings"
)

type ActionRequst map[string]interface{}

func (r ActionRequst) Get(name string) string {

	v, ok := r[name]
	if !ok {
		return ""
	}

	return v.(string)
}

func ActionHandler(prbc *net.NetUDP, p *net.NetPacket) {

	var f interface{}
	err := json.Unmarshal(p.Body, &f)
	if err != nil {
		return
	}

	req := f.(map[string]interface{})
	action, ok := req["action"]
	if !ok {
		return
	}

	//fmt.Println("v2 dispatchEvent -> ", action.(string), "\n\t", req)

	ip := strings.Split(p.Addr, ":")[0]

	switch action.(string) {

	case base.ActionPeerCast:
		MemberPeerCast(req, ip)

	case base.ActionLeaderNew:
		MemberLeaderNew(req, ip)
	case base.ActionLeaderAccept:
		MemberLeaderAccept(req, ip)
	case base.ActionLeaderValue:
		MemberLeaderValue(req, ip)
	case base.ActionLeaderCast:
		MemberLeaderCast(req, ip)

		// case "WatchEvent":
		// 	ActionWatchEvent(req, ip)
		// case "WatchLease":
		// 	ActionWatchLease(req, ip)

	}
}

// func ActionWatchLease(req ActionRequst, addr string) {

// 	if !req.isset("path") || !req.isset("host") || !req.isset("ttl") {
// 		return
// 	}

// 	path := strings.Trim(req["path"].(string), "/")
// 	ttlen, _ := strconv.Atoi(req["ttl"].(string))
// 	ttl := time.Now().Unix() + int64(ttlen)

// 	watcherlock.Lock()
// 	if w, ok := watches[path]; ok {
// 		if i, ok := w[req["host"].(string)]; ok {
// 			if ttl > i {
// 				w[req["host"].(string)] = ttl
// 			}
// 		}
// 	}
// 	watcherlock.Unlock()

// 	return
// }

// func ActionWatchEvent(req ActionRequst, addr string) {

// 	if !req.isset("path") || !req.isset("event") {
// 		return
// 	}

// 	//Println("WE", req)
// 	// ###TODO###
// 	//agent.watchmq <- &WatcherQueue{req["path"].(string), req["event"].(string), 0}
// }
